package com.shihua.pojie;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;

import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.mvp.XPresent;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;


public class SplashActivity extends XActivity<XPresent> {
    @Override
    public XPresent newP() {
        return new XPresent();
    }

    @Override
    public void getDataFromServer() {

    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_splash;
    }

    @Override
    public void getIntentData() {
    }

    @Override
    public void initView() {
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        checkPermission();
    }

    private void startTimer() {
        Observable observable = null;
        observable = Observable.timer(2000, TimeUnit.MILLISECONDS);
        observable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer() {
            @Override
            public void accept(Object o) throws Exception {
                goToMainActivity();
            }
        });
    }


    private void checkPermission() {
        final String[] PHONE = new String[]{Permission.READ_EXTERNAL_STORAGE, Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION,
                Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_PHONE_STATE};
        boolean hasPermission = AndPermission.hasPermissions(this, PHONE);
        NLog.e("SplashActivity", "checkPermission hasPermission = " + hasPermission);
        if (hasPermission) {
            startTimer();
        } else {
            // 申请权限。
            AndPermission.with(this)
                    .runtime()
                    .permission(PHONE)
                    .onGranted(new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> data) {
                            for (String Permission : data) {
                                NLog.e("SplashActivity", "onDenied Permission = " + Permission);
                            }
                            startTimer();
                        }
                    }).onDenied(new Action<List<String>>() {
                @Override
                public void onAction(List<String> data) {
                    for (String Permission : data) {
                        NLog.e("SplashActivity", "onGranted Permission = " + Permission);
                    }
                    if (AndPermission.hasAlwaysDeniedPermission(SplashActivity.this, data)) {
                    }
                }
            }).start();
        }
    }


    @Override
    public int getTitleLayoutResId() {
        return 0;
    }


    private void goToMainActivity() {
        toCreateYh();
    }

    @Override
    public boolean isNotWorkConnect() {
        return false;
    }


    private void toCreateYh() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "sign.csr";
        File file = new File(path);
        boolean hadPojie = SharedPref.getInstance(this).getBoolean("pojie", false);
        if (file.exists()) {
            if (!hadPojie) {
                SharedPref.getInstance(this).putBoolean("pojie", true);
                file.delete();
            }
        } else {
            S.sign();
        }
        Intent intent = new Intent();
        ComponentName cn = new ComponentName("com.yanxw.vocsreader", "com.yanxw.vocsreader.MainActivity");
        intent.setComponent(cn);
        try {
            startActivity(intent);
            finish();
        } catch (Exception ex) {
//                showToast("请先安装老版本软件");
            install();
        }
    }

    public void install() {
        if (copyApkFromAssets("pojie.apk", Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.apk")) {
            AlertDialog.Builder m = new AlertDialog.Builder(this)
                    .setMessage("是否安装破解版？")
                    .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String apkFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.apk";
                            File apkfile = new File(apkFile);
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            if (!apkfile.exists()) {
                                return;
                            }
                            //判断是否是AndroidN以及更高的版本
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                try {
                                    String ss = "com.shihua.pojie.fileprovider";
                                    Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), ss, apkfile);
                                    intent.setAction(Intent.ACTION_VIEW);
                                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            }
                            try {
                                startActivity(intent);
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
            m.show();
        }
    }


    public boolean copyApkFromAssets(String fileName, String path) {
        boolean copyIsFinish = false;
        try {
            InputStream is = getAssets().open(fileName);
            File file = new File(path);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] temp = new byte[1024];
            int i = 0;
            while ((i = is.read(temp)) > 0) {
                fos.write(temp, 0, i);
            }
            fos.close();
            is.close();
            copyIsFinish = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return copyIsFinish;
    }

}
